package web

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"zsc-boot/core"
)

const ginConfKey = "gin"

type Gin struct {
	Port int    `mapstructure:"port"`
	Name string `mapstructure:"version"`
	Mode string `mapstructure:"mode"`
}

var (
	Srv       *http.Server
	app       gin.IRouter
	routerMap = make(map[string]gin.IRouter)
)

func (d *Gin) load() {
	gin.SetMode(d.Mode)

	//初始化gin服务
	tmp := gin.New()
	Srv = new(http.Server)
	Srv.Addr = fmt.Sprintf(":%d", d.Port)
	Srv.Handler = tmp

	routerMap["/"] = tmp.Group("/")
	routerMap["public"] = tmp.Group("/")
	app = tmp
}

func GetGin(path ...string) gin.IRouter {
	if app == nil {
		//获取配置
		conf, err := core.Conf[Gin](ginConfKey)
		if err != nil {
			panic(err)
		}
		conf.load()
	}

	if len(path) == 0 {
		path = []string{"/"}
	}

	if routerGroup, ok := routerMap[path[0]]; ok {
		return routerGroup
	}
	routerMap[path[0]] = app.Group(path[0])
	return routerMap[path[0]]
}

func Run() {
	// 开启一个goroutine启动服务
	if err := Srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		panic(err)
	}
}

func SuccessResponse(ctx *gin.Context, data interface{}) {
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功!",
		"data": data,
	})
}

type PageResult struct {
	List     interface{} `json:"list"`
	Total    int64       `json:"total"`
	Page     int         `json:"page"`
	PageSize int         `json:"pageSize"`
}

func SuccessListResponse(ctx *gin.Context, data any, total int64, page, pageSize int) {
	ctx.JSON(200, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功！",
		"data": PageResult{
			List:     data,
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	})
}

func FailResponse(ctx *gin.Context, err error, msg string) {
	var errMsg string
	if err != nil {
		errMsg = err.Error()
	}
	ctx.AbortWithStatusJSON(http.StatusOK, gin.H{
		"code": 500,
		"msg":  msg,
		"data": nil,
		"err":  errMsg,
	})
}
